//
//  AppDelegate.m
//  tcpoctest
//
//  Created by gump on 10/18/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewManager.h"
#import "MainViewController.h"
#import "netManager.h"
#import "LogicControl.h"
#import "DataBaseCtrol.h"
#import "MapManager.h"
#import "PromptLoginDataSource.h"
#import "userdb.h"
#import "sendLoginBypp.h"
#import "sendLogin.h"
#import "UMSocial.h"
#import "LoginViewController.h"
#import "CompleteViewController.h"

@implementation AppDelegate

- (void)dealloc
{
}




- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] ;
    
    WINDOW_WIDTH = [[UIScreen mainScreen] bounds].size.width;
    WINDOW_HIGTH = [[UIScreen mainScreen] bounds].size.height;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self initControls];
    
    [[FileManager shareControl] createPath];
    [[netManager sharedNetManager] creatConnect];
    [[LogicControl sharedLogicControl] beginRecv];
    [[MapManager shareControl] initBaiduMap];
    
    [ViewManager sharedViewManager].mywindow = self.window;
    [[ViewManager sharedViewManager] viewStart];
    
    [[DataControl shareControl].LCDS addLogicCommand:LC_READVER];
    
    [UMSocialData setAppKey:T_UMENG];
    [MobClick startWithAppkey:T_UMENG];
    
    [[UIApplication sharedApplication]
     registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge |
      UIRemoteNotificationTypeSound |
      UIRemoteNotificationTypeAlert)];
    
//    CompleteInfoViewController * completeInfoVC = [[CompleteInfoViewController alloc] init];
//    self.window.rootViewController = completeInfoVC;
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    //[[DataControl shareControl] addLogicCommand:LC_BACKGROUND];
    
    
    [self beingBackgroundUpdateTask];
    
    [[DataControl shareControl] SetGameState:GMS_CHANGEGROUND];
    
    [[netManager sharedNetManager] SendQuitDirectly];
    
    [[netManager sharedNetManager] closeConnect];
    [DataControl shareControl].blogin = false;
    
    [self endBackgroundUpdateTask];
    
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    //[[DataControl shareControl] addLogicCommand:LC_FOREGROUND];
    [[netManager sharedNetManager] creatConnect];
    //给与ios启动线程的时间
    sleep(1);
    
    if ([DataControl shareControl].miOldGameState != GMS_LOGIN &&
        [DataControl shareControl].miOldGameState != GMS_CONFIG)
    {
        [[DataControl shareControl].promptloginDS SetIsShowMain:false];
        [[DataControl shareControl].promptloginDS SetIsPromptLogin:true];
        [[DataControl shareControl].promptloginDS SetIsInitData:false];
        
        [DataControl shareControl].personDS.uinfo.mail = getLocalMail();
        
        NSString *strppnum = [NSString stringWithFormat:@"%d",
                              getLocalPP()];
        
        if (![strppnum isEqualToString:@"-1"]) {
            [[ViewManager sharedViewManager].loginvc SetMail:strppnum];
        }
        
    
        if ([[DataControl shareControl].personDS.uinfo.mail isEqualToString:@""])
        {
            [DataControl shareControl].personDS.uinfo.ppNumber = getLocalPP();
            if ([DataControl shareControl].personDS.uinfo.ppNumber != -1)
            {
                [DataControl shareControl].personDS.uinfo.ps =
                [[DataBaseCtrol shareControl].userdatabase searchPSByPP:[DataControl shareControl].personDS.uinfo.ppNumber];
                if ([[DataControl shareControl].personDS.uinfo.ps isEqualToString:@""])
                {
                    [[ViewManager sharedViewManager] showView:VI_LOGIN
                  withIsRemoveCurV:false
                     withDirection:VD_RIGHT];
                }
                else
                {
                    [[DataControl shareControl] SetLoginType:LT_PP];
                    
                    [[netManager sharedNetManager].sendloginpp SendLoginWithPPP:
                     [DataControl shareControl].personDS.uinfo.ppNumber
                                                                         withPS:
                     [DataControl shareControl].personDS.uinfo.ps];
                    
                }
            }
            else
            {
                [[ViewManager sharedViewManager] showView:VI_LOGIN
              withIsRemoveCurV:false
                 withDirection:VD_RIGHT];
            }
        }
        else
        {
            [DataControl shareControl].personDS.uinfo.ps =
            [[DataBaseCtrol shareControl].userdatabase searchPS:[DataControl shareControl].personDS.uinfo.mail];
            
            if ([[DataControl shareControl].personDS.uinfo.ps isEqualToString:@""])
            {
                [[ViewManager sharedViewManager] showView:VI_LOGIN
              withIsRemoveCurV:false
                 withDirection:VD_RIGHT];
            }
            else
            {
                [[DataControl shareControl] SetLoginType:LT_MAIL];
                
                [[netManager sharedNetManager].sendlonginbymail sendLoginByMail:
                 [DataControl shareControl].personDS.uinfo.mail
                                                                         withPS:
                 [DataControl shareControl].personDS.uinfo.ps];
            }
        }
    }
    else
    {
        [[DataControl shareControl] SetGameState:[DataControl shareControl].miOldGameState];
    }
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)initControls
{
    [FileManager shareControl];
    [DataControl shareControl];
    [netManager sharedNetManager];
    [DataBaseCtrol shareControl];
}

- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    
    NSString *tokenStr = [deviceToken description];
    NSString *pushToken = [[[tokenStr
                             stringByReplacingOccurrencesOfString:@"<" withString:@""]
                            stringByReplacingOccurrencesOfString:@">" withString:@""]
                           stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
    if ([DataControl shareControl].personDS != nil) {
        [DataControl shareControl].personDS.strToken = pushToken;
    }
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

@end
